package com.hzhr.iot.log.aop;

import com.hzhr.iot.core.dto.ResponseExceptionDto;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.HttpServerErrorException;


@Aspect
@Component
@Order(1)
public class HttpAspect {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Pointcut("execution(* com.hzhr.iot.log.controller..*(..))")
    public void httpPointCut() {
    }

    @Before("httpPointCut()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
    }

    @AfterReturning(returning = "ret", pointcut = "httpPointCut()")
    public void doAfterReturning(Object ret) throws Throwable {
    }

    @Around("httpPointCut()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        try {
            return joinPoint.proceed();
        } catch (HttpClientErrorException e) {
            logger.error("未知异常", e);
            ResponseExceptionDto responseExceptionDto = new ResponseExceptionDto();
            responseExceptionDto.setCode(e.getStatusCode().value());
            responseExceptionDto.setDes(e.getStatusCode().getReasonPhrase());
            return new ResponseEntity<>(responseExceptionDto, e.getStatusCode());
        }  catch (HttpServerErrorException e) {
            logger.error("未知异常", e);
            ResponseExceptionDto responseExceptionDto = new ResponseExceptionDto();
            responseExceptionDto.setCode(e.getStatusCode().value());
            responseExceptionDto.setDes(e.getStatusCode().getReasonPhrase());
            return new ResponseEntity<>(responseExceptionDto, e.getStatusCode());
        } catch (Throwable e) {
            logger.error("未知异常", e);
            ResponseExceptionDto responseExceptionDto = new ResponseExceptionDto();
            responseExceptionDto.setCode(500);
            responseExceptionDto.setDes("内部异常");
            return new ResponseEntity<>(responseExceptionDto, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}